package com.css.crm.ws.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ResourceBundle;

public class WebServiceClient {

	private static final String WEBSERVICE_PROPERTIES = "com.css.ws.config.webservice";
	private static ResourceBundle rb = ResourceBundle.getBundle(WEBSERVICE_PROPERTIES);
	
	public static String createCustomer(String customerXml){
		try {
			URL url = new URL(rb.getString("url_create_customer"));
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept", "text/plain");
			conn.setDoOutput(true); 
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
			writer.write(customerXml);
			writer.flush();
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output = br.readLine();
			writer.close();
			conn.disconnect();
			return output;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		
	}
	
	public static String updateCustomer(String customerXml){
		try {
			URL url = new URL(rb.getString("url_update_customer"));
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept", "text/plain");
			conn.setDoOutput(true); 
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
			writer.write(customerXml);
			writer.flush();
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output = br.readLine();
			writer.close();
			conn.disconnect();
			return output;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		
	}
	
	public static String searchCustomer(String keyWord) {
		try {
			URL url = new URL(rb.getString("url_search_customer") + "?keyWord=" + keyWord);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "text/plain");
			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output = br.readLine();
			conn.disconnect();
			return output;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

}
